package org.tourism.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.beans.factory.annotation.Value;
import org.tourism.entity.Image;
import org.tourism.mapper.ImageMapper;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

@Service
public class OssService {
    @Autowired
    private OSS ossClient;

    @Autowired
    private ImageMapper imageMapper;

    @Value("${oss.bucketName}")
    private String bucketName;

    @Value("${oss.endpoint}")
    private String endpoint;

    //上传一个文件，返回文件的url
    public String uploadImage(MultipartFile file, String savePath) throws IOException {
        ossClient.putObject(new PutObjectRequest(bucketName, savePath, file.getInputStream()));
        return "https://" + bucketName + "." + endpoint.replace("https://", "") + "/" + savePath;
    }

    public void saveImage(String imageUrl) throws IOException {
        Image image = new Image();
        image.setImagepath(imageUrl);
        imageMapper.insert(image);
    }

    public void downloadImage(String image, String path) throws IOException {
        try {
            // 下载文件
            OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, image));

            // 将OSS文件保存到本地文件
            OutputStream outputStream = new FileOutputStream(path);

            // 将OSS文件流保存到本地文件
            int bytesRead;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ossObject.getObjectContent().read(buffer, 0, buffer.length)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
